﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Sita.MainModule.Services;
using Sita.Entities;
using Sita.Presentation.ViewModels;

namespace Sita.Presentation.Controllers
{
    public class DeliveryNoteController : DefaultController
    {
        DeliveryNoteService deliveryNoteService;

        public DeliveryNoteController()
        {
            deliveryNoteService = new DeliveryNoteService();
        }

        public ActionResult Index()
        {
            return View();
        }

        public PartialViewResult List(int? index, string sortColumn, bool? sortAscending, int? pageSize, int? deliveryNoteID, int? customerID)
        {
            int TotalRows;

            int CurrentBusinessUnitID = this.AuthenticatedUser.Business[this.AuthenticatedUser.CurrentBusinessUnitIndex].BusinessUnitID;
            sortAscending = sortAscending ?? true;
            index = index ?? 0;
            deliveryNoteID = deliveryNoteID ?? 0;
            customerID = customerID ?? 0;
            if (string.IsNullOrEmpty(sortColumn))
                sortColumn = "DeliveryNoteID";
            if (!pageSize.HasValue)
                pageSize = 5;

            ViewData["PageSizeFilter"] = new SelectList(new int[] { 5, 10, 15, 20 });

            return PartialView(
                    new GenericGridList<DeliveryNote>(
                        deliveryNoteService.GetPaginatedDeliveryNotesByFilter(CurrentBusinessUnitID, index.Value, pageSize.Value,
                        sortColumn, sortAscending.Value, customerID.Value, deliveryNoteID.Value, out TotalRows), index.Value, sortColumn, pageSize.Value,
                        TotalRows, sortAscending.Value));
        }

        [HttpGet]
        public ActionResult CreateOrUpdate(int? id)
        {
            DeliveryNote deliveryNote;
            if (id.HasValue)
            {
                deliveryNote = deliveryNoteService.GetDeliveryNoteByIDWithItemsAndCustomer(id.Value);
                ViewData["CustomerName"] = deliveryNote.Customer.CompanyName;
            }
            else
            {
                deliveryNote = new DeliveryNote();
                ViewData["CustomerName"] = "";
            }
            return View(deliveryNote);
        }

        [HttpPost]
        public JsonResult CreateOrUpdate(DeliveryNote deliveryNote)
        {
            DeliveryNote currentDeliveryNote;
            DeliveryNote originalDeliveryNote = null;

            currentDeliveryNote = deliveryNote;

            if (currentDeliveryNote.DeliveryNoteID == 0)
            {
                currentDeliveryNote.BusinessUnitID = this.AuthenticatedUser.Business[this.AuthenticatedUser.CurrentBusinessUnitIndex].BusinessUnitID;
                deliveryNoteService.AddDeliveryNote(currentDeliveryNote);
            }
            else
            {
                originalDeliveryNote = deliveryNoteService.GetDeliveryNoteByIDWithItems(currentDeliveryNote.DeliveryNoteID);
                originalDeliveryNote.CustomerID = currentDeliveryNote.CustomerID;
                originalDeliveryNote.CreationDate = currentDeliveryNote.CreationDate;

                //Add new items
                foreach (var item in currentDeliveryNote.DeliveryNoteReplacements)
                {
                    if (originalDeliveryNote.DeliveryNoteReplacements.Where(dn => dn.ReplacementID == item.ReplacementID && dn.Quantity == item.Quantity && dn.UnitPrice == item.UnitPrice && dn.TotalPrice == item.TotalPrice).FirstOrDefault() == null)
                    {
                        originalDeliveryNote.DeliveryNoteReplacements.Add(new DeliveryNoteReplacement()
                        {
                            DeliveryNoteID = currentDeliveryNote.DeliveryNoteID,
                            ReplacementID = item.ReplacementID,
                            Quantity = item.Quantity,
                            UnitPrice = item.UnitPrice,
                            TotalPrice = item.TotalPrice
                        });
                    }
                }
                //Remove items that have been deleted
                foreach (var item in originalDeliveryNote.DeliveryNoteReplacements.ToList())
                {
                    if (currentDeliveryNote.DeliveryNoteReplacements.Where(dn => dn.ReplacementID == item.ReplacementID && dn.Quantity == item.Quantity && dn.UnitPrice == item.UnitPrice && dn.TotalPrice == item.TotalPrice).FirstOrDefault() == null)
                    {
                        item.MarkAsDeleted();
                    }
                }

                deliveryNoteService.ModifyDeliveryNote(originalDeliveryNote);
            }

            JsonResult Response = new JsonResult();
            Response.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return Json(Response);
        }

        public JsonResult LockStock(int? id)
        {
            string Result;
            Dictionary<string, object> ResultDetails;
            ResultDetails = new Dictionary<string, object>();
            if (id.HasValue)
            {
                Result = deliveryNoteService.ValidateStockAndLock(id.Value);

                if (Result == "SUCCESS")
                {
                    ResultDetails["Success"] = true;
                }
                else
                {
                    ResultDetails["Success"] = false;
                    ResultDetails["Message"] = Result;
                
                }
                
            }
        
            JsonResult Response = new JsonResult();
            Response.Data = ResultDetails;


            return Response;
        }

        public ActionResult Print(int? id)
        {
            DeliveryNote deliveryNote = deliveryNoteService.GetDeliveryNoteByIDWithItemsAndCustomer(id.Value);
            return View(deliveryNote);
        }

        public JsonResult GetAvailableDeliveryNotesByCustomerID(int customerID)
        {
            IList<DeliveryNote> deliveryNotes;
            deliveryNotes = deliveryNoteService.GetAvailableDeliveryNotesByCustomerID(customerID);
            return Json(deliveryNotes, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetDeliveryNoteByID(int deliveryNoteID)
        {
            DeliveryNote deliveryNote;
            deliveryNote = deliveryNoteService.GetDeliveryNoteByIDWithItems(deliveryNoteID);
            deliveryNote.DeliveryNoteReplacements = null;//Evita Circular Json Exception
            return Json(deliveryNote, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public PartialViewResult Filter()
        {
            CustomerService customerService = new CustomerService();
            ViewData["CustomerListFilter"] = new SelectList(customerService.GetCustomersByBusinessUnitID(this.AuthenticatedUser.Business[this.AuthenticatedUser.CurrentBusinessUnitIndex].BusinessUnitID,string.Empty), "CustomerId", "FullName");

            return PartialView(new FilterModel() { PageSize = 5 });
        }
    }
}
